<template>
  <view class="containerDateT">
    <view class="time-picker-group">
      <view @click="openStartPopup()">
        <up-input placeholder="开始时间" border="surround" v-model="startTimeDisplay"
          :customStyle="{ width: '83vw', pointerEvents: 'none' }" readonly></up-input>
      </view>
      <view style="margin: 10px 0;">至</view>
      <view @click="openEndPopup()">
        <up-input placeholder="结束时间" border="surround" v-model="endTimeDisplay"
          :customStyle="{ width: '83vw', pointerEvents: 'none' }" readonly></up-input>
      </view>
    </view>

    <!-- 开始时间选择器 -->
    <up-datetime-picker :title="'开始时间'" :show="showStart" v-model="startDateValue" mode="datetime"
      :closeOnClickOverlay="true" @close="closePopup" @cancel="showStart = false" @confirm="confirmStartDate">
    </up-datetime-picker>

    <!-- 结束时间选择器 -->
    <up-datetime-picker :title="'结束时间'" :show="showEnd" v-model="endDateValue" mode="datetime"
      :closeOnClickOverlay="true" @close="closePopup" @cancel="showEnd = false" @confirm="confirmEndDate">
    </up-datetime-picker>
  </view>
</template>

<script>
import {
  useUserStore
} from '@/pinia-store/user'
import {
  mapStores
} from 'pinia'

export default {
  props: {
    itemIndex: {
      type: Number,
      default: 0
    },
    value: {
      type: String,
      default: null
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    format: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    ApplyDetailList: {
      type: Array,
      default: () => {
        return []
      }
    },
    itemId: {
      type: String,
      required: true
    },
    titleItems: {
      type: String,
      default: null
    },
    label: {
      type: String,
      default: null
    },
    TableListValue: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data () {
    return {
      // 日期选择
      showStart: false,
      showEnd: false,
      startDateValue: Number(new Date()),
      endDateValue: Number(new Date()),
      // 显示值
      startTimeDisplay: '',
      endTimeDisplay: '',
      // 存储值
      startTimeValue: '',
      endTimeValue: '',
      valueDate: []
    }
  },
  computed: {
    ...mapStores(useUserStore)
  },
  created () {
    this.startTimeDisplay = this?.TableListValue[0] || '';
    this.endTimeDisplay = this?.TableListValue[1] || '';
    this.startTimeValue = this?.TableListValue[0] || '';
    this.endTimeValue = this?.TableListValue[1] || '';
    this.valueDate = this?.TableListValue || []
    let value = uni.getStorageSync('formData');
    let formItems = JSON.parse(value.formItems);
    formItems.forEach(item => {
      if (item.title == this.title) {
        uni.removeStorageSync(`${item.id}`);
      }
    })
  },
  mounted () {
    this.setechodata()
  },
  watch: {
    valueDate: {
      handler (newValue) {
        let value = uni.getStorageSync('formData');
        let formItems = JSON.parse(value.formItems);
        formItems.forEach(item => {
          if (item.title == this.title) {
            item.value = newValue;
            uni.setStorageSync(item.id, newValue);
          } else if (this.titleItems == item.title) {
            item.props.columns.forEach(columnsitem => {
              if (columnsitem.title == this.label) {
                columnsitem.value = newValue;
                uni.setStorageSync(columnsitem.id, newValue);
              }
            })
          }
        })
      },
      deep: true
    }
  },
  methods: {
    setechodata () {
      // 添加数据回显逻辑
      if (this.ApplyDetailList && this.ApplyDetailList.formData && this.itemId) {
        // 检查 formData 中是否存在当前 itemId 对应的字段 
        if (this.ApplyDetailList.formData.hasOwnProperty(this.itemId)) {
          // 获取对应的值
          const fieldValue = this.ApplyDetailList.formData[this.itemId];

          if (Array.isArray(fieldValue) && fieldValue.length > 0) {
            this.startTimeDisplay = fieldValue[0] || ''
            this.endTimeDisplay = fieldValue[1] || ''
            this.valueDate = fieldValue || []
            this.startTimeValue = fieldValue[0] || ''
            this.endTimeValue = fieldValue[1] || ''
          }
        }
      }
    },
    openStartPopup () {
      this.showStart = true;
    },
    openEndPopup () {
      this.showEnd = true;
    },

    // 开始时间日期选择
    confirmStartDate (value) {
      this.startDateValue = value.value;
      const datetimeStr = this.formatDateTime(this.startDateValue);

      const selectedStart = new Date(datetimeStr);
      const selectedEnd = new Date(this.endTimeValue);

      // 校验：开始时间不能晚于结束时间
      if (this.endTimeValue && selectedStart > selectedEnd) {
        uni.showToast({
          title: '开始时间不能晚于结束时间',
          icon: 'none'
        });
        // 清空开始时间
        this.startTimeDisplay = '';
        this.startTimeValue = '';
        this.startDateValue = Number(new Date())
        this.showStart = false;
        this.updateValueDate();
        return;
      }

      this.startTimeDisplay = datetimeStr;
      this.startTimeValue = datetimeStr;
      this.showStart = false;

      this.updateValueDate();
    },

    // 结束时间日期选择
    confirmEndDate (value) {
      const selectedEndTime = value.value;
      const endDate = new Date(selectedEndTime);
      const startDate = new Date(this.startTimeValue);

      if (endDate < startDate) {
        uni.showToast({
          title: '结束时间不能早于开始时间',
          icon: 'none'
        });
        return;
      }
      this.endDateValue = value.value;
      const datetimeStr = this.formatDateTime(this.endDateValue);

      this.endTimeDisplay = datetimeStr;
      this.endTimeValue = datetimeStr;
      this.showEnd = false;

      this.updateValueDate();
    },
    formatDateTime (timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    closePopup () {
      this.showStart = false;
      this.showEnd = false;
      this.showStartPeriod = false;
      this.showEndPeriod = false;
    },
    // 更新存储的值
    updateValueDate () {
      if (this.startTimeDisplay && this.endTimeDisplay) {
        this.valueDate = [this.startTimeValue, this.endTimeValue];
        this.$emit('selectedTableList');
      } else {
        this.valueDate = null
        this.$emit('selectedTableList');
      }
    }
  }
}
</script>

<style>
.time-picker-group {
  display: flex;
  flex-direction: column;
}

.containerDateT {
  background-color: #ffffff;
}
</style>
